package com.globalwave.db.seq.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.sql.DataSource;

import com.globalwave.common.cache.CodeHelper;
import com.globalwave.db.exception.DBException;

public class BaseSequence {

	private Connection connection  ;
	
	protected Connection getConnection() {
		try {
			if (connection == null) {
			    this.connection = ((DataSource)CodeHelper.getAppContext().getBean("dataSource")).getConnection() ;
			} 

			return this.connection ;
		} catch (Exception e) {
			throw new DBException(e) ;
		}
	}
	

	protected long getLong(String sql, Object... params) {
		PreparedStatement st = null ;
		ResultSet rs = null ;
		try {
		    st = getConnection().prepareStatement(sql) ;
		    
		    int i = 1 ;
		    for (Object param:params) {
		        st.setObject(i++, param) ;	
		    }
		    rs = st.executeQuery() ;
		    
		    if (rs.next()) {
		    	return rs.getLong(1) ;
		    } else {
		    	return -1L ;
		    }
		} catch (Exception e) {
			throw new DBException(e) ;
		} finally {
			if (st != null) {
				try {
					st.close() ;
				} catch (Exception e) {
					throw new DBException(e) ;
				}
			}
			if (rs != null) {
				try {
					rs.close() ;
				} catch (Exception e) {
					throw new DBException(e) ;
				}
			}
		}
		
	}
}
